package com.moblie.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.moblie.constant.MessageConstant;
import com.moblie.constant.RedisMessageConstant;
import com.moblie.domain.User;
import com.moblie.entity.Result;
import com.moblie.service.UserService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.sql.Date;

/**
 * 描述:
 *
 * @author 景远超
 * @create 2020-05-30 13:39
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/login")
    public Result login(@RequestBody User user, HttpServletResponse response) {
        // 1、校验用户输入的短信验证码是否正确，
        String telephone = user.getPhone();
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = user.getCheckcode();
        if (codeInRedis != null && validateCode != null && codeInRedis.equals(validateCode)) {
            //2、如果验证码正确，则判断当前用户是否为会员，如果不是会员则自动完成会员注册
            User user1 = userService.findByTelephone(telephone);
            if (user1 == null) {//new对象,封装,
                User user2 = new User();
                user2.setPhone(telephone);
                user2.setRegistTime(new Date(new java.util.Date().getTime()));
                userService.add(user2);
            }
            //3、向客户端写入Cookie，内容为用户手机号
            Cookie cookie = new Cookie("login_user_telephone", telephone);
            cookie.setPath("/");
            response.addCookie(cookie);
            //4、将会员信息保存到Redis，使用手机号作为key，保存时长为30分钟
            String json = (String) JSON.toJSON(user1);
            jedisPool.getResource().setex(telephone, 60 * 30, json);
            return new Result(true, com.moblie.constant.MessageConstant.LOGIN_SUCCESS);
        } else {
            //如果验证码错误则登录失败
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

}
